import axios from 'axios'
import {ElMessage} from 'element-plus'
//import { refresh } from '../api/userLogin'
import {getToken} from '@/utils/auth'
import router from "../router";

const service = axios.create({
    baseURL: '/api',
    timeout: 50000
})

// 请求拦截: 每一次发请求都会做的事情
service.interceptors.request.use(
    config => {
        const token = getToken() as string
        if (token) {
            config.headers!['Authorization'] = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)


//响应拦截
service.interceptors.response.use((response) => {
    return response.data
}, (err) => {
    console.log(err)
    const res = err
    if (res.response.status === 404) {
        ElMessage.closeAll();
        ElMessage({
            message: '访问异常，请联系管理员',
            type: 'error',
            duration: 2 * 1000
        })
    } else if (res.response.status === 500) {
        ElMessage.closeAll();
        ElMessage({
            message: '网络异常，请检查网络',
            type: 'error',
            duration: 2 * 1000
        })
        router.push({path: '/login'}).then(r => {
            location.reload()
        })
    }

    return Promise.reject(err)
})

export default service
